Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

shell - How to use sed and cut to find and replace value at certain position of line in a file

I have a case where I have to replace the number 1 with number 3 at 10th location of various lines in a stored text file. I am unable to find a way to do that. Below is sample file and code.

Sample file:

$ cat testdata.txt
1  43515 8 1 victor    Samuel    20190112
3215736  4 6 Michael   pristine  20180923
1  56261 1 1 John      Carter    19880712
#!/bin/sh
filename=testdata.txt
echo "reading number of line"
nol=$(cat $filename | wc -l)
flag[$nol]=''
echo "reading content of file"
for i in (1..$nol)
do
flag=($cut -c10-11 $filename)
if($flag==1)
sed 's/1/3/2'
fi
done

But this is not working.

Please help to resolve this.

Updated:

Sample Output:

1  43515 8 1 victor    Samuel    20190112
3215736  4 6 Michael   pristine  20180923
1  56261 3 1 John      Carter    19880712
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try this

sed "s/^(.{8}) 1 (.*)$/1 3 2/g" testdata.txt > new_testdata.txt

If sed supports the option -i you can also edit inplace.

sed -i "s/^(.{8}) 1 (.*)$/1 3 2/g" testdata.txt

output

1  43515 8 1 victor     Samuel 20190112
3215736 4 6 Michael pristine 20180923
1  56261 3 1 John      Carter    19880712

explanation

s              # substitute
/^(           # from start of line, save into arg1
.{8}         # the first 8 characters
) 1 (        # search pattern ' 1 '
.*             # save the rest into arg2
)$/           # to the end of the line
1 3 2        # output: arg1 3 arg2
/g             # global on whole line

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...