Substring in UNIX Substring in UNIX unix unix

Substring in UNIX


Actually shell parameter expansion lets you do substring slicing directly, so you could just do:

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

Update

To do this over an entire file, read the line in a loop:

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

(By the way, bash slicing is zero-indexed, so if you want the numbers '3', '6' and '8' you'd really want ${x:2:1} ${x:5:1} and {$x:7:1}.)


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

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

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


To "generalize" this on a file you can pipe it after a cat like so:

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


Perl one-liner.

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