【问题标题】:Need to update substring in last line of few files having last line start with fixed string in linux需要更新最后一行文件的最后一行中的子字符串,最后一行在linux中以固定字符串开头
【发布时间】:2019-07-17 07:02:07
【问题描述】:

我需要更新最后一行以特定字符串开头的所有文件中字符串的第一个和第二个管道之间的文本。请帮我找到linux命令

文件abc.txt 包含以下数据:

Name|city|salary
xyz|pun|450000
Footer|355|02052019|895

目录中还有其他文件,但是我只需要更新最后一行以Footer 开头的文件。要更新的文本是第一次和第二次出现 | 之间的文本

【问题讨论】:

标签: linux grep


【解决方案1】:

不确定输出应该是什么,但是如果第一个字段是Footer,这会将第二个字段更改为一些新字段

awk '$1=="Footer" {$2="new"}1' FS="|" OFS="|" abc.txt
Name|city|salary
xyz|pun|450000
Footer|new|02052019|895

【讨论】:

    【解决方案2】:

    先切换到工作目录。

    初始文件如下:

    Name|city|salary
    xyz|pun|450000
    Footer|355|02052019|895
    

    脚本从这里开始:

    srch="Footer"   # keyword to search at last of file.
    
    for file_name in `ls`   # iterate all files in current directory
        do
        last_line_first_word="`tail -1 $file_name | cut -d "|" -f 1-1`"   # first word of the last line
    
        if [ "$srch" == "$last_line_first_word" ]   # if last word match proceed with replace
            then
            awk -F "|" '{$2="replace_string"; print; }' $file_name > dummy.txt  # replace second column with user string
            sed -i 's/ /|/g' dummy.txt   # replace <spaces> with "|" 
            sed -i '' 's/ /|/g' dummy.txt  # replace <spaces> with "|" [ In MAC ]
            mv dummy.txt  $file_name        # rename to original filename
            echo "File modified ->> "$file_name
        fi
        echo "File NOT modified "$file_name
    done
    

    结果文件:

    Name|replace_string|salary
    xyz|replace_string|450000
    Footer|replace_string|02052019|895
    

    希望这会有所帮助。

    日志:

    File NOT modified Applications
    File NOT modified Desktop
    File NOT modified Documents
    File NOT modified Downloads
    File NOT modified IdeaProjects
    File NOT modified Library
    File NOT modified Movies
    File NOT modified Music
    File NOT modified Pictures
    File NOT modified Public
    File NOT modified PycharmProjects
    File modified ->> test.txt
    File NOT modified test.txt
    

    【讨论】:

      【解决方案3】:

      另一种方法是使用sed 替换第一个'|' 之后的第一组数字的值。您可以使用sed 替换形式sed '/locate/s/find/replace/' file 找到以^Footer 开头的行并找到|[0-9][0-9]* 并将那里的数字替换为您喜欢的任何数字(比如|322 而不是355

      您可以通过向sed 提供-i 选项来就地进行更改。对你来说,这看起来像:

      $ sed -i '/^Footer/s/|[0-9][0-9]*/|322/' file
      

      以及更改后的结果数据文件:

      $ cat file
      Name|city|salary
      xyz|pun|450000
      Footer|322|02052019|895
      

      有几种替代方法可以解决此问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-26
        • 2020-08-10
        • 1970-01-01
        • 2019-05-11
        • 2013-09-12
        相关资源
        最近更新 更多