I have a eg file op.txt
This is a cat
This is a fat cat
This is a fat black cat
I want to remove only the word cat from the first alone .can somebody help.
I have a eg file op.txt
This is a cat
This is a fat cat
This is a fat black cat
I want to remove only the word cat from the first alone .can somebody help.
sed -i '1{s/\w*\W*$//;}' op.txt
Try also
awk 'NR == 1 {$NF = ""} 1' file
This is a
This is a fat cat
This is a fat black cat
awk 'NR == 1 {sub (/cat$/, "")} 1' file
This is a
This is a fat cat
This is a fat black cat
awk: syntax error near line 1
awk: bailing out near line 1
--- Post updated at 07:02 PM ---
sed: illegal option -- i
error am receiveing
printf "1 s/\\\w*\\\W*$//\nw\nq\n" | ed - op.txt
Might have been smart to mention your OS version...
Remove the first word in line 2
sed '2 s/^ *[^ ]\{1,\} *//' op.txt
Line 2, s(ubstitute) what the BRE ^ *[^ ]\{1,\} *
matches with nothing.
BRE: at the beginning of the line any spaces then at least one non-space then any spaces.
Remove the last word in line 1
sed '1 s/ *[^ ]\{1,\} *$//' op.txt
Line 1, s(ubstitute) what the BRE *[^ ]\{1,\} *$
matches with nothing.
BRE: any spaces then at least one non-space then any spaces at the end of the line.
@rdrtx1, \w and \W and \s and \S are defined in the Perl RE, a newer glibc (GNU-Linux) is needed.
If portability mattters then stick to the original: perl.
perl -i -lpe '$.==1 and s/\s*\S+\s*$//' op.txt
The -i option writes the output back to the input file.
Depending of the purpose, if you are in a shell script and need to do this, you might:-
while read line
do
cut_line="${line% *}" # Note that the space is the literal space in the input line
echo "This is the value of \$cut_line \"${cut_line}\""
done < op.txt
Of course, you could do other things within the loop should you choose.
I hope that this helps,
Robin