Substring on UNIX

Suppose I have the string "123456789".

I want to extract the third, sixth and eighth elements. I think I can use

cut -3, -6, -8

But if it gives

368

Suppose I want to separate them with a space to get

3 6 8

What should I do?

+4
source share
4 answers

You can use the sed tool and issue this command in your number:

sed -r "s/^..(.)..(.).(.).*$/\1 \2 \3/"

Explained by RegEx: http://regex101.com/r/fH7zW6


To "generalize" this to a file, you can pass it after catso:

cat file.txt|sed -r "s/^..(.)..(.).(.).*$/\1 \2 \3/"
+1
source

In fact, expanding the shell parameter allows you to perform direct division of the substring, so you can simply do:

x='123456789'
echo "${x:3:1}" "${x:6:1}" "${x:8:1}"

Update

, :

while read x; do
  echo "${x:3:1}" "${x:6:1}" "${x:8:1}"
done < file

(, bash slicing , , "3", "6" "8", ${x:2:1} ${x:5:1} and {$x:7:1}.)

+2

Perl is one line.

perl -lne '@A = split //; print "$A[2] $A[5] $A[7]"' file
+1
source

Usage cut:

$ cat input
1234567890
2345678901
3456789012
4567890123
5678901234
$ cut -b3,6,8 --output-delimiter=" " input
3 6 8
4 7 9
5 8 0
6 9 1
7 0 2

The parameter -bselects only the specified bytes. The output separator can be specified with --output-delimiter.

+1
source

All Articles