如何使用sed和cut在文件中某行的特定位置查找和替换值 [英] How to use sed and cut to find and replace value at certain position of line in a file

查看:83
本文介绍了如何使用sed和cut在文件中某行的特定位置查找和替换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我必须在存储的文本文件中各行的第10个位置用数字3替换数字1.我无法找到一种方法来做到这一点.下面是示例文件和代码.

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.

示例文件:

$ 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

但这不起作用.

请帮助解决此问题.

已更新:

样本输出:

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

推荐答案

尝试一下

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

如果sed支持选项-i,您还可以就地编辑.

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

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

输出

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

说明

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

这篇关于如何使用sed和cut在文件中某行的特定位置查找和替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆