cancel
Showing results for 
Search instead for 
Did you mean: 

cut specific characters

ivywong1
Occasional Contributor

cut specific characters

I would like to use a script to cut a string from a file ( test.txt ) , cut the string on line 2 , from the second character , cut 3 characters from it , the result should as "ran" , can advise how to do it ? Thanks


$vi test.txt
apple
orange
pine
banana
4 REPLIES
kemo
Trusted Contributor

Re: cut specific characters

put this in a script
=====================
cat test.txt |head -2 |tail -1 |cut -c 2-4


you need to save it in a variable.
var=`cat /test |head -2 |tail -1 |cut -c 2-4`
Mel Burslan
Honored Contributor

Re: cut specific characters

or

sed -ne "2,2p" test.txt|cut -c 2,4

if you want to assign it to variable to use it later

MYVARIABLE=$(sed -ne "2,2p" test.txt|cut -c 2,4)

$() construct is the newer and more appropriate form of the command quoted in backticks. FO the time being, both work the same way.
________________________________
UNIX because I majored in cryptology...

Re: cut specific characters

Hello,

awk 'NR == 2 { print substr ( $0, 2, 3 ) }' test.txt

Cheers

Jean-Philippe
Dennis Handly
Acclaimed Contributor

Re: cut specific characters

>Jean-Philippe: awk 'NR == 2 { print substr($0, 2, 3) }' test.txt

You may want to optimize this by adding "exit" so you don't read all zillion lines of the file:
awk 'NR == 2 { print substr($0, 2, 3); exit }' test.txt