如何使用Bash测试文件中是否存在字符串?

本文翻译自:How to test if string exists in file with Bash?

I have a file that contains directory names: 我有一个包含目录名称的文件:

my_list.txt : my_list.txt

/tmp
/var/tmp

I'd like to check in Bash before I'll add a directory name if that name already exists in the file. 如果文件中已经存在目录名称,我想先检查一下Bash。


#1楼

参考:https://stackoom.com/question/JvW6/如何使用Bash测试文件中是否存在字符串


#2楼

Three methods in my mind: 我想到的三种方法:

1) Short test for a name in a path (I'm not sure this might be your case) 1)对路径中的名称进行简短测试(我不确定这可能是您的情况)

ls -a "path" | grep "name"


2) Short test for a string in a file 2)对文件中的字符串进行简短测试

grep -R "string" "filepath"


3) Longer bash script using regex: 3)使用正则表达式的更长的bash脚本:

#!/bin/bash

declare file="content.txt"
declare regex="\s+string\s+"

declare file_content=$( cat "${file}" )
if [[ " $file_content " =~ $regex ]] # please note the space before and after the file content
    then
        echo "found"
    else
        echo "not found"
fi

exit

This should be quicker if you have to test multiple string on a file content using a loop for example changing the regex at any cicle. 如果您必须使用循环来测试文件内容上的多个字符串 (例如在任何cicle上更改正则表达式),则此方法应该更快


#3楼

Regarding the following solution: 关于以下解决方案:

grep -Fxq "$FILENAME" my_list.txt

In case you are wondering (as I did) what -Fxq means in plain English: 如果您想知道(与我一样) -Fxq用简单的英语含义:

  • F : Affects how PATTERN is interpreted (fixed string instead of a regex) F :影响PATTERN的解释方式(固定字符串而不是正则表达式)
  • x : Match whole line x :匹配整行
  • q : Shhhhh... minimal printing q :嘘...最少印刷

From the man file: 从man文件中:

-F, --fixed-strings
    Interpret  PATTERN  as  a  list of fixed strings, separated by newlines, any of which is to be matched.
    (-F is specified by POSIX.)
-x, --line-regexp
    Select only those matches that exactly match the whole line.  (-x is specified by POSIX.)
-q, --quiet, --silent
    Quiet; do not write anything to standard output.  Exit immediately with zero status  if  any  match  is
          found,  even  if  an error was detected.  Also see the -s or --no-messages option.  (-q is specified by
          POSIX.)

#4楼

Simpler way: 更简单的方法:

if grep "$filename" my_list.txt > /dev/null
then
   ... found
else
   ... not found
fi

Tip: send to /dev/null if you want command's exit status, but not outputs. 提示:如果要命令的退出状态,请发送至/dev/null ,但不输出。


#5楼

if grep -q "$Filename$" my_list.txt
   then
     echo "exist"
else 
     echo "not exist"
fi

#6楼

If you just want to check the existence of one line, you do not need to create a file. 如果只想检查一行是否存在,则无需创建文件。 Eg, 例如,

if grep -xq "LINE_TO_BE_MATCHED" FILE_TO_LOOK_IN ; then
  # code for if it exists
else
  # code for if it does not exist
fi  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值