简体   繁体   English

Bash 脚本使用 sed 到 append 行在文件末尾,如果 Mac 上不存在该行

[英]Bash script using sed to append line at end of file if line doesn't exist on mac

I need to use sed instead of echo and append to the end of a file: list.txt我需要使用 sed 而不是 echo 和 append 到文件末尾:list.txt

list.txt has a list of directories: list.txt 有一个目录列表:

/desktop/test1/file1 /桌面/test1/file1

/desktop/test2/file1 /桌面/test2/file1

I need to append another directory with slashes to this list.txt at the end of the file if that directory already doesn't exist in the list.如果列表中已经不存在该目录,我需要 append 另一个目录,该目录在文件末尾带有斜杠到此 list.txt。 Such as: /desktop/file1 The result should be:如:/desktop/file1 结果应该是:

/desktop/test1/file1 /桌面/test1/file1

/desktop/test2/file1 /桌面/test2/file1

/desktop/file1 /桌面/文件1

I've tried using this script but am running into syntax errors with the a command which I've been seeing could be a mac issue?:我试过使用这个脚本,但是我看到的命令遇到语法错误,我看到这可能是一个 mac 问题?:

#!/bin/bash
if ! grep -q "/desktop/file1" user/admin/Desktop/list.txt; then
    sed -i -e '$a/desktop/file1' user/admin/Desktop/list.txt
fi

The a command is used as a\ in standard sed and should be followed by a newline and the text to be written. a命令在标准sed中用作a\ ,后跟换行符和要写入的文本。 The form you use is a GNU extension.您使用的形式是 GNU 扩展。 So a standard sed command to do the job could be:因此,完成这项工作的标准sed命令可能是:

sed -i '' '$a\
/desktop/file1' user/admin/Desktop/list.txt

or或者

sed -i '' '$a\'$'\n''/desktop/file1' user/admin/Desktop/list.txt

using ANSI-C quoting in bash.在 bash 中使用 ANSI-C 引用。

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

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