如何在Bash中的引号之间提取字符串

时间:2018-07-26 09:08:34

标签: linux bash shell

我需要提取文件中引号之间的字符串。

例如:我的文件名为test.txt,它具有以下内容:

"Hello_World"

我正在从bash中阅读以下内容:

string="$(head -1 test.txt)"
echo $string 

这将打印"Hello_World",但我需要Hello_World

任何帮助将不胜感激。谢谢。

3 个答案:

答案 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.