简体   繁体   English

bash 脚本将文本附加到文件的第一行

[英]bash script append text to first line of a file

I want to add a text to the end of the first line of a file using a bash script.我想使用 bash 脚本将文本添加到文件第一行的末尾。 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.该文件是 /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 脚本的了解不足以在这里找到解决方案,以及所有我在网上找到的示例添加文件中每一行的开头/结尾,而不仅仅是第一行。

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开关:

sed -i ' 1 s/.*/&123/' yourfile.txt

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' :这是在/etc/passwd的第一行添加“ok”的解决方案,我认为您可以在脚本中使用一点“调整”:

$ awk 'NR==1{printf "%s %s\n", $0, "ok"}' /etc/passwd
root:x:0:0:root:/root:/bin/bash ok

To edit a file, you can use ed , the standard editor:编辑文件,您可以使用标准编辑器ed

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

ed 's commands: ed的命令:

  • 1 : go to line 1 1 : 转到第 1 行
  • a : append (this will insert after the current line) a : append (这将在当前行之后插入)
  • We're in insert mode and we're inserting the expansion of $line我们处于插入模式,我们正在插入$line的扩展
  • . : stop insert mode : 停止插入模式
  • 1,2j join lines 1 and 2 1,2j连接第 1 行和第 2 行
  • w : write w : 写
  • q : quit q : 退出

This can be used to append a variable to the first line of input:这可用于将变量附加到输入的第一行:

awk -v suffix="$suffix" '{print NR==1 ? $0 suffix : $0}'

This will work even if the variable could potentially contain regex formatting characters.即使变量可能包含正则表达式格式字符,这也将起作用。

Example:例子:

suffix=' [first line]'
cat input.txt | awk -v suffix="$suffix" '{print NR==1 ? $0 suffix : $0}' > output.txt

input.txt:输入.txt:

Line 1
Line 2
Line 3

output.txt:输出.txt:

Line 1 [first line]
Line 2
Line 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM