我需要提取文件中引号之间的字符串。
例如:我的文件名为test.txt
,它具有以下内容:
"Hello_World"
我正在从bash中阅读以下内容:
string="$(head -1 test.txt)"
echo $string
这将打印"Hello_World"
,但我需要Hello_World
。
任何帮助将不胜感激。谢谢。
答案 0 :(得分:0)
您可以简单地使用sed
来读取第一行,也可以过滤掉"
,然后尝试执行以下命令,
sed -n '1 s/"//gp' test.txt
简要说明,
-n
:禁止自动打印1
:仅匹配第一行s/"//gp
:过滤掉"
,然后打印该行答案 1 :(得分:0)
您可以使用纯bash
来执行此操作,而无需生成任何外部程序:
read -r line < test.txt ; line=${line#\"} ; line=${line%\"} ; echo $line
read
实际上是读整行的,而这两个赋值实际上是在行的开头或结尾去除了任何单引号。
我假设您不想删除字符串本身内的任何引号,所以我将其两端限制为一个。
它还使您能够成功地读取行 ,而无需使用前导引号,尾随引号或同时使用这两个行。
答案 2 :(得分:-1)
您可以使用tr
:
echo "$string " | tr -d '"'
来自man tr
:
DESCRIPTION
tr
实用程序通过替换或删除所选字符将标准输入复制到标准输出。以下选项可用:
-C Complement the set of characters in string1, that is ``-C ab'' includes every character except for `a' and `b'. -c Same as -C but complement the set of values in string1. -d Delete characters in string1 from the input.