在我的项目中,我有一个文件1。
此文件1的内容如下:
HISTSIZE=1000
if [ "$HISTCONTROL" = "ignorespace" ] ; then
export HISTCONTROL=ignoreboth
else
export HISTCONTROL=ignoredups
fi
export PATH USER LOGNAME MAIL
# By default, we want umask to get set.
# Current threshold for system .
现在我想在后面加上一句话:
export PATH USER LOGNAME MAIL
这句话是
export PROMPT_COMMAND='echo "`date +%Y-%m-%d" "%H:%M:%S`","`who`" >> linshi'
所以我写了一个cmdRecord.sh脚本:
newLine="export PROMPT_COMMAND='echo \"`date +%Y-%m-%d\" \"%H:%M:%S`\",\"`who`\" >> linshi'"
baseLN="export PATH USER LOGNAME MAIL"
sed -i '/$baseLN/a$newLine' file1
执行后:sh cmdRecord.sh,file1的正确内容应为:
HISTSIZE=1000
if [ "$HISTCONTROL" = "ignorespace" ] ; then
export HISTCONTROL=ignoreboth
else
export HISTCONTROL=ignoredups
fi
export PATH USER LOGNAME MAIL
export PROMPT_COMMAND='echo "`date +%Y-%m-%d" "%H:%M:%S`","`who`" >> linshi'
# By default, we want umask to get set.
# Current threshold for system .
但不幸的是,它失败了,新句子未显示在file1中。
我尝试过:
sed -i“ / $ baseLN / a $ addNL”文件1
但是该命令在新行中执行,结果是:
HISTSIZE=1000
if [ "$HISTCONTROL" = "ignorespace" ] ; then
export HISTCONTROL=ignoreboth
else
export HISTCONTROL=ignoredups
fi
export PATH USER LOGNAME MAIL
export PROMPT_COMMAND='echo 2019-07-09 11:45:08,"root pts/0 2019-07-09 11:38 (ln01)" >> linshi'"
# By default, we want umask to get set.
# Current threshold for system .
新行已更改!! 似乎没有错,谁可以帮助我?
答案 0 :(得分:0)
newLine="export PROMPT_COMMAND=\'echo \"\`date +%Y-%m-%d\" \"%H:%M:%S\`\",\"\`who\`\" >> linshi\'"
效果很好
答案 1 :(得分:0)
您必须撤消带有转义符的bash字符“和`的特殊含义:
sed "/export PATH USER LOGNAME MAIL/a export PROMPT_COMMAND='echo \"\`date +%Y-%m-%d\" \"%H:%M:%S\`\",\"\`who\`\" >> linshi'" file1
使用选项-i(sed -i ...),可以内联修改文件。
答案 2 :(得分:0)
您的第一个挑战是按需要填充新行。 您可以避免使用https://serverfault.com/a/72511
的语法添加反斜杠IFS= read -r -d '' newLine <<"END"
export PROMPT_COMMAND='echo "`date +%Y-%m-%d" "%H:%M:%S`","`who`" >> linshi'
END
您可以使用
进行sed
命令
baseLN="export PATH USER LOGNAME MAIL"
cmd=$(printf "/%s/a%s" "${baseLN}" "${newLine}")
sed "${cmd}" file1
答案 3 :(得分:0)
这可能对您有用(GNU sed和Bash):
cat <<\! | sed -i '/export PATH USER LOGNAME MAIL/r /dev/stdin' file
export PROMPT_COMMAND='echo "`date +%Y-%m-%d" "%H:%M:%S`","`who`" >> linshi'
!