bash Sed - 删除字符串前的 x 个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20836736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:07:09  来源:igfitidea点击:

Sed - Delete x numbers of characters before a string

regexlinuxbashcommand-linesed

提问by user3145872

I have a txt file and I want to delete x number of characters before a specific string

我有一个 txt 文件,我想删除特定字符串之前的 x 个字符

Example :

例子 :

52.451878252 foo 845.851878212 foo
98.444854655 foo 458.344854656 foo

I want to delete 8 characters before the string ' foo' in order to get this :

我想删除字符串 'foo' 之前的 8 个字符以获得这个:

52.45 foo 845.66 foo
98.44 foo 458.66 foo

How should I do with the sed command (or something else) ?

我应该如何处理 sed 命令(或其他命令)?

Thank you :)

谢谢 :)

回答by janos

Here you go:

干得好:

sed -e 's/........foo/ foo/g' file.txt

Or equivalently:

或等效地:

sed -e 's/.\{8\}foo/ foo/g' file.txt

Or even:

甚至:

sed -e 's/.\{8\}\(foo\)/ /g' file.txt

Or a different approach, with the same output for your sample:

或者采用不同的方法,对您的样本使用相同的输出:

sed -e 's/[0-9]\{7\} / /g' file.txt

回答by John B

If your goal is to round each float down to the second decimal point, you could use printf.

如果您的目标是将每个浮点数四舍五入到第二个小数点,您可以使用printf.

while read line; do
    printf "%0.2f %s %0.2f %s\n" $line
done < file.txt