简体   繁体   中英

Delete the first character of certan line in file in shell script

Here I want to delete the first character of file of certain lines. For example:

>cat file1.txt
10081551
10081599
10082234
10082259
20081134
20081159
30082232
10087721

From 3rd line to 7th line delete the first character sed command or any else and output will be:

>cat file1.txt
10081551
10081599
0082234
0082259
0081134
0081159
0082232
10087721
sed -i '3,7s/.//' file1.txt

sed -i.bak '3,7s/.//' file1.txt # to keep backup

From 3rd to 7th line, replace the first character with nothing.

This is simple in either sed:

sed -i '3,7 s/^.//'

or Perl:

perl -i -pe 's/^.// if $. >= 3 && $. <= 7'

The sed program can do this with:

pax$ sed '3,7s/.//' file1.txt
10081551
10081599
0082234
0082259
0081134
0081159
0082232
10087721

substituting the first character on the line that matches . (which is the first character on the line).

I'll also provide an awk solution. It's a little more complex but it's worth learning since it allows for much more complex operations than sed .

pax$ awk 'NR>=3&&NR<=7{sub("^.","",$0)}{print}' file1.txt
10081551
10081599
0082234
0082259
0081134
0081159
0082232
10087721

For your 2nd question:

  1. if the ending quote is on the last line of the file:

     sed '$i\\ /home/neeraj/yocto/poky/meta-ti \\\\ ' text 
  2. to match the end of the continued lines (this one feels fragile)

     sed ' /BBLAYERS.*"/ { :a /\\\\$/ {N; ba} s@"$@/home/neeraj/yocto/poky/meta-ti \\\\\\n"@ } ' text 

Another variation of the awk

awk 'NR~/^[3-7]$/{sub(".","")}1' file
10081551
10081599
0082234
0082259
0081134
0081159
0082232
10087721

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM