Shell 如何使用sed和cut查找和替换文件中某行位置的值
我有一个例子,我必须在存储的文本文件中不同行的第10个位置将数字1替换为数字3。我找不到一个办法来做那件事。下面是示例文件和代码 示例文件:Shell 如何使用sed和cut查找和替换文件中某行位置的值,shell,unix,sed,cut,Shell,Unix,Sed,Cut,我有一个例子,我必须在存储的文本文件中不同行的第10个位置将数字1替换为数字3。我找不到一个办法来做那件事。下面是示例文件和代码 示例文件: $ cat testdata.txt 1 43515 8 1 victor Samuel 20190112 3215736 4 6 Michael pristine 20180923 1 56261 1 1 John Carter 19880712 但这是行不通的 请帮助解决此问题 更新: 样本输出: 1 435
$ cat testdata.txt
1 43515 8 1 victor Samuel 20190112
3215736 4 6 Michael pristine 20180923
1 56261 1 1 John Carter 19880712
但这是行不通的
请帮助解决此问题
更新:
样本输出:
1 43515 8 1 victor Samuel 20190112
3215736 4 6 Michael pristine 20180923
1 56261 3 1 John Carter 19880712
试试这个
如果sed支持选项-i,您也可以就地编辑
sed -i "s/^\(.\{8\}\) 1 \(.*\)$/\1 3 \2/g" testdata.txt
输出
解释
请看一看:您还需要提供一个示例输出。你对这个问题的描述相当简洁,而且有点不清楚。这看起来不适合这项工作。使用更倾向于字符串操作的编程语言(如awk、perl或python)怎么样?使用其中一个可能会非常简单,而且大多数linux系统都预装了所有这些脚本。使用shell脚本的原因是,我使用pig将复杂数据存储在hive外部表中,然后在一些操作后由shell生成文件。一些小的改进:您不需要全局标志。匹配“1”后的子字符串已过时。当sed支持它时。标志-r有助于避免反斜杠:sed-ri的/^.{8}1/\1 3/'testdata.txtdowner@UtLax,这很有帮助。你的解释对理解这个表达有很大帮助。
sed "s/^\(.\{8\}\) 1 \(.*\)$/\1 3 \2/g" testdata.txt > new_testdata.txt
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