【问题标题】:Command for printing part of a String? [closed]打印部分字符串的命令? [关闭]
【发布时间】:2019-10-03 02:06:02
【问题描述】:

我有一个文件名test, 它包含一个字符串James Bond 007, 我只想打印James Bond。 我尝试了以下命令:

$ strings -n 2 test
$ sed -n '/James/,/Bond/p' test
$ awk '{print substr($1,10)}' test

【问题讨论】:

标签: linux macos unix terminal command


【解决方案1】:

要打印前两个字,可以使用awk

awk '{print $1, $2}' test

要打印前十个字符,可以将文件内容放在一个变量中,然后使用bash子字符串操作:

contents=$(cat test)
echo "${contents:0:10}"

或者在awk:

awk '{print substr($0, 1, 10)}' test

请注意$0 表示整行,您必须为substr() 提供起始索引和长度。 awk 中的索引从 1 而不是 0 开始。

sed中,/James/,/Bond/是一个行范围表达式;它处理从包含James 的行到包含Bond 的行的所有行。它不只处理部分行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 2023-02-15
    • 1970-01-01
    相关资源
    最近更新 更多