【问题标题】:Remove everything after a changing string [duplicate]更改字符串后删除所有内容[重复]
【发布时间】:2021-02-28 21:09:13
【问题描述】:

我遇到了以下问题;

作为输入,我得到几行文件路径如下:

root/child/abc/somefile.txt
root/child/def/123/somefile.txt
root/child/ghijklm/somefile.txt

root/child 始终在路径中,之后的一切都可能不同。

我想删除孙文件夹之后的所有内容。所以输出将是:

root/child/abc/
root/child/def/
root/child/ghijklm/

我尝试了以下方法:

sed 's/\/child\/.*/\/child\/.*/'

当然,这只会给出以下输出:

root/child/.*
root/child/.*
root/child/.*

任何帮助将不胜感激!

【问题讨论】:

  • 使用 GNU awk:awk '{NF=3; NF++}1' FS=/ OFS=/ file

标签: regex linux bash sed cut


【解决方案1】:

这可能对你有用(GNU sed):

sed -E 's/^(([^/]*[/]){3}).*/\1/' file

删除第三组非正斜杠/斜杠之后的所有内容。

【讨论】:

    【解决方案2】:

    使用 Perl:

    perl -pe 's{ ^ ( ( [^/]+ / ){3} ) .* $ }{$1}x' in_file > out_file
    

    Perl 单行程序使用这些命令行标志:
    -e:告诉 Perl 查找内联代码,而不是在文件中。
    -p:循环输入一行一次,默认分配给$_。在每次循环迭代后添加print $_

    正则表达式使用此修饰符:
    x:为了可读性,忽略空格和 cmets。

    替换语句,解释:
    ^:行首。
    $:行尾。
    [^/]+ /:一个或多个非斜杠字符(@ 987654334@),后跟一个斜线。
    ( [^/]+ / ){3} :一个或多个非斜线字符,后跟一个斜线,正好重复 3 次。
    ( ( [^/]+ / ){3} ) :上面,用括号捕获匹配的部分到第一个捕获变量$1 中,稍后在替换中使用。捕获组从左到右计数。
    .*:任何字符出现零次或多次。
    s{THIS}{THAT}:将@​​987654340@ 替换为THAT

    另请参阅:
    perldoc perlrun: how to execute the Perl interpreter: command line switches
    perldoc perlre: Perl regular expressions (regexes)
    perldoc perlre: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups
    perldoc perlrequick: Perl regular expressions quick start

    【讨论】:

      【解决方案3】:

      你很亲密。

      sed 's%\(/child/[^/]*\)/.*%\1%'
      

      正则表达式[^/]* 匹配尽可能多的非斜线字符;然后我们只用括号中捕获的部分替换整个匹配项,有效地修剪掉其余部分。

      【讨论】:

        【解决方案4】:

        With awk:您能否尝试在 GNU awk 中使用所示示例进行跟踪、编写和测试。

        awk 'match($0,/root\/child\/[^/]*/){print substr($0,RSTART,RLENGTH)}' Input_file
        

        说明:为上述添加详细说明。

        awk '                              ##Starting awk program from here.
        match($0,/root\/child\/[^/]*/){    ##Using match function to match root/child/... till next / in current line.
          print substr($0,RSTART,RLENGTH)  ##printig substring from RSTART to till RLENGTH.
        }
        ' Input_file                       ##Mentioning Input_file name here.
        

        sed

        sed 's/.*\(root\/child\/[^/]*\).*/\1/' Input_file
        

        解释: 使用sed 的替换方法匹配root/child/ till next occurrence of / 并将其保存到临时缓冲区(反向引用方法)并用仅匹配的替换整行反向引用的值。

        【讨论】:

          【解决方案5】:

          带剪切:

          cut -d\/ -f1,2,3 file
          

          【讨论】:

          • 或:cut -d / -f 1-3 file
          猜你喜欢
          • 2018-04-03
          • 1970-01-01
          • 2019-02-11
          • 2012-10-19
          • 2018-03-01
          • 1970-01-01
          • 2018-11-15
          • 2017-06-03
          • 1970-01-01
          相关资源
          最近更新 更多