使用 shell 脚本隔离文本文件的某些部分

问题描述 投票:0回答:2
//unit-translator

#head
<

shell: /bin/bash;

>

#stuffs
<

[~]: ~;
[binary's]: /bin/bash;
[run-as-root]: sudo;


>

#commands
<

make-directory:mkdir;
move-to-directory:cd;
url-download-current-directory:wget;
extract-here-tar:tar;
copy:cp;
remove-directory-+files:rm -R;
enter-root:su;

>

我想将“#commands”之后、两个“<", ">”之间的所有内容隔离为字符串。我该怎么办?

我把整个填充物做成了一根绳子

translator=$(<config.txt)

我想隔离命令部分中的所有内容,并将其存储为变量“翻译命令”。

从那时起,我计划分割每一行,每组命令如下所示:

IFS=';' read -a translatorcommandlines <<< "$translatorcommands"
IFS=':' read -a translatorcommand <<< "$translatorcommandlines"

我很无知,请帮助我!

bash shell sh
2个回答
2
投票

如果您想提取

#command
之后
<
>
之间的所有行,您可以使用以下命令:

sed '0,/^#command/d' config.txt | sed '/>/q' | grep "^\w"

它会跳过

#command
之前的所有行,打印直到
>
为止的行,并且仅获取以单词字符开头的行。

我的文件输出是:

make-directory:mkdir;
move-to-directory:cd;
url-download-current-directory:wget;
extract-here-tar:tar;
copy:cp;
remove-directory-+files:rm -R;
enter-root:su;

1
投票

UNIX 的通用文本处理工具是“awk”。您没有在问题中显示您希望输出什么,所以我不知道您想要什么,但希望这足以让您从这里弄清楚:

$ cat tst.awk
BEGIN { RS=">"; FS="\n" }
{ gsub(/^.*<[[:blank:]]*\n|\n[[:blank:]]*$/,"") }
NF {
    for (i=1;i<=NF;i++) {
        print "record", NR, "field", i, "= [" $i "]"
    }
    print "----"
}

$ awk -f tst.awk file
record 1 field 1 = []
record 1 field 2 = [shell: /bin/bash;]
record 1 field 3 = []
----
record 2 field 1 = []
record 2 field 2 = [[~]: ~;]
record 2 field 3 = [[binary's]: /bin/bash;]
record 2 field 4 = [[run-as-root]: sudo;]
record 2 field 5 = []
record 2 field 6 = []
----
record 3 field 1 = []
record 3 field 2 = [make-directory:mkdir;]
record 3 field 3 = [move-to-directory:cd;]
record 3 field 4 = [url-download-current-directory:wget;]
record 3 field 5 = [extract-here-tar:tar;]
record 3 field 6 = [copy:cp;]
record 3 field 7 = [remove-directory-+files:rm -R;]
record 3 field 8 = [enter-root:su;]
record 3 field 9 = []
----
© www.soinside.com 2019 - 2024. All rights reserved.