bash 脚本将文本附加到文件的第一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26958327/
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 script append text to first line of a file
提问by Ryu Kajiya
I want to add a text to the end of the first line of a file using a bash script. The file is /etc/cmdline.txt which does not allow line breaks and needs new commands seperated by a blank, so text i want to add realy needs to be in first line.
我想使用 bash 脚本将文本添加到文件第一行的末尾。该文件是 /etc/cmdline.txt,它不允许换行,需要用空格分隔的新命令,所以我想添加的文本确实需要在第一行。
What i got so far is:
到目前为止我得到的是:
line=' bcm2708.w1_gpio_pin=20'
file=/boot/cmdline.txt
if ! grep -q -x -F -e "$line" <"$file"; then
printf '%s' "$line\n" >>"$file"
fi
But that appends the text after the line break of the first line, so the result is wrong. I either need to trim the file contend, add my text and a line feed or somehow just add it to first line of file not touching the rest somehow, but my knowledge of bash scripts is not good enough to find a solution here, and all the examples i find online add beginning/end of every line in a file, not just the first line.
但是在第一行的换行符之后追加文本,所以结果是错误的。我要么需要修剪文件竞争,添加我的文本和换行符,要么以某种方式将它添加到文件的第一行而不以某种方式触及其余部分,但我对 bash 脚本的了解不足以在这里找到解决方案,所有我在网上找到的示例添加文件中每一行的开头/结尾,而不仅仅是第一行。
回答by Skynet
This sed
command will add 123
to end of first line of your file.
此sed
命令将添加123
到文件第一行的末尾。
sed ' 1 s/.*/&123/' yourfile.txt
also
还
sed '1 s/$/ 123/' yourfile.txt
For appending result to the same file you have to use -i
switch :
要将结果附加到同一个文件,您必须使用-i
switch :
sed -i ' 1 s/.*/&123/' yourfile.txt
回答by Gilles Quenot
This is a solution to add "ok" at the first line on /etc/passwd
, I think you can use this in your script with a little bit of 'tuning' :
这是在第一行添加“ok”的解决方案/etc/passwd
,我认为您可以在脚本中使用一点“调整”:
$ awk 'NR==1{printf "%s %s\n", line=' bcm2708.w1_gpio_pin=20'
file=/boot/cmdline.txt
if ! grep -q -x -F -e "$line" <"$file"; then
ed -s "$file" < <(printf '%s\n' 1 a "$line" . 1,2j w q)
fi
, "ok"}' /etc/passwd
root:x:0:0:root:/root:/bin/bash ok
回答by gniourf_gniourf
To edita file, you can use ed
, the standard editor:
要编辑文件,您可以使用ed
标准编辑器:
ed
's commands:
ed
的命令:
1
: go to line 1a
: append (this will insert after the current line)- We're in insert mode and we're inserting the expansion of
$line
.
: stop insert mode1,2j
join lines 1 and 2w
: writeq
: quit
1
: 转到第 1 行a
: append (这将在当前行之后插入)- 我们处于插入模式,我们正在插入扩展
$line
.
: 停止插入模式1,2j
连接第 1 行和第 2 行w
: 写q
: 退出