【问题标题】:How to use sed and cut to find and replace value at certain position of line in a file如何使用 sed 和 cut 在文件中行的特定位置查找和替换值
【发布时间】:2019-08-21 03:34:29
【问题描述】:

我有一个案例,我必须在存储的文本文件中的各个行的第 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
#!/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

【问题讨论】:

  • 请看:shellcheck.net
  • 您还需要提供示例输出。您对问题的描述相当简洁,有点不清楚
  • 这看起来不像是适合这项工作的工具。使用更面向字符串操作的编程语言(如 awk、perl 或 python)怎么样?用其中一个来做会相当简单,而且大多数 linux 系统都预装了它们。
  • 使用 shell 脚本的原因是,我使用 pig 将复杂数据存储在 hive 外部表中,然后在经过一些操作后通过 shell 生成文件。

标签: shell unix sed cut


【解决方案1】:

试试这个

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

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

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

【讨论】:

  • 一些小的改进:您不需要全局标志。匹配 ` 1 ` 之后的子字符串已过时。当sed 支持时。标志-r 有助于避免反斜杠:sed -ri 's/^(.{8}) 1 /\1 3 /' testdata.txt
  • 感谢@UtLax,这帮助很大。你的解释对理解这个表达很有帮助。
猜你喜欢
  • 2019-04-29
  • 2017-09-12
  • 2017-08-07
  • 1970-01-01
  • 2010-12-20
  • 2021-10-06
  • 2012-02-14
  • 2016-11-21
  • 1970-01-01
相关资源
最近更新 更多