繁体   English   中英

如何使用shell脚本将文本附加到文件中的特定行?

[英]How to append text to a specific lines in a file using shell script?

我有一个文本文件(file.txt),其内容类似于:

foo1 3464 
foo2 3696 
foo3 4562 

它包含过程和相应的PID。

根据PID,我想使用shell脚本,在这个文件中追加一个字符串(运行/不运行)。

例如,在上面的文件中,对于包含PID 3696的行,我想在末尾附加一个字符串“running”,以便该文件变为:

foo1 3464 
foo2 3696 running
foo3 4562 

我该怎么做?

$ sed '/3696/ s/$/running/' file.txt 
foo1 3464 
foo2 3696 running
foo3 4562 

要么

$ sed 's/3696/& running/' file.txt 
foo1 3464 
foo2 3696 running 
foo3 4562 

添加-i选项以将更改保存回file.txt

使用循环迭代文件中的行并运行ps以检查进程是否正在运行:

while IFS= read -r line
do
    pid="$(awk '{print $NF}' <<< $line)"
    unset status
    if ps --no-headers -p "$pid" > /dev/null
    then
        status="running"
    fi
    echo "$line $status"
done < file
awk '$2==3696{$3="running";}1' your_file


>cat temp
foo1 3464 
foo2 3696 
foo3 4562 
> awk '$2==3696{$3="running";}1' temp
foo1 3464 
foo2 3696 running
foo3 4562 
> 

暂无
暂无

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

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