bash 替换;删除字符串后的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2378443/
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
Bash substitution; remove everything after the string
提问by Open the way
This is probably a very stupid question, but in Bash I want to do the following substitution:
这可能是一个非常愚蠢的问题,但在 Bash 中我想做以下替换:
I have in some files the line:
我在一些文件中有一行:
DATE: 12 jan 2009, weather 20°C
日期:2009 年 1 月 12 日,天气 20°C
and I want to change it to
我想把它改成
DATE: XXXX
日期:XXXX
Using sedI guess I had to say "starting after "DATE:", please remove the rest and insert " XXXX".
使用sed我想我不得不说“在“日期:”之后开始,请删除其余部分并插入“XXXX”。
Is this approach OK and how can I perform it?
这种方法可以吗,我该如何执行?
Also, I want to learn. If you were in my situation what would you do? Ask here or spend one hour looking at the man page? Where would you start from?
还有,我想学。如果你处于我的处境,你会怎么做?在这里提问还是花一小时看手册页?你会从哪里开始?
采纳答案by ghostdog74
while read line
do
echo "${line/#DATE*/DATE:xxxxx}"
done < myfile
回答by codaddict
Try:
尝试:
sed -i 's/^DATE:.*$/DATE: XXXX/g' filename
Answer to your 2nd question depends on how often you need to write such things. If it's a one time thing and time is limited it's better to ask here. If not, it's better to learn how to do it by using an online tutorial.
你的第二个问题的答案取决于你需要多久写一次这样的东西。如果这是一次性的事情并且时间有限,最好在这里询问。如果没有,最好通过使用在线教程来学习如何做到这一点。
回答by muruga
You can use the following code also
您也可以使用以下代码
> var="DATE: 12 jan 2009, weather 20oC"
> echo $var | sed -r 's!^(DATE:).*$! XXXX!'
回答by ghostdog74
You can use the shell
你可以使用外壳
while IFS=":" read -r a b
do
case "$a" in
DATE* ) echo "$a:XXXX";;
*) echo "$a$b" ;;
esac
done < "file"
or awk
或 awk
$ cat file
some line
DATE: 12 jan 2009, weather 20oC
some line
$ awk -F":" '~/^DATE/{="XXXX"}1' OFS=":" file
some line
DATE:XXXX
some line
回答by David V.
If your line isn't in a file, you can do it without sed :
如果您的行不在文件中,则无需 sed 即可:
var="DATE: 12 jan 2009, weather 20oC"
echo "${var/DATE:*/DATE:xxxxx}"

