检查行是否以标点符号结尾;如果没有,请添加期间

时间:2014-03-18 21:25:01

标签: bash unix

我想检查一行是否以标点符号(。,?!)结尾,如果没有,则添加句号。

A button is missing!
A button on their back allowed them to hug
A cat is carried by the scruff of its neck by a teenage boy?
A cattery is where cats are commercially housed

输出:

A button is missing!
A button on their back allowed them to hug.
A cat is carried by the scruff of its neck by a teenage boy?
A cattery is where cats are commercially housed.

我真的很难过,我试着点击字符串的最后一个字符 - 有什么帮助吗?

4 个答案:

答案 0 :(得分:5)

使用sed:

sed -i.bak 's/[^[:punct:]]$/&./' file
A button is missing!
A button on their back allowed them to hug.
A cat is carried by the scruff of its neck by a teenage boy?
A cattery is where cats are commercially housed.

答案 1 :(得分:1)

使用awk

awk '!/[[:punct:]]$/ && NF{$NF=$NF"."}1' file

<强>解释

  • 我们使用!/[[:punct:]]$/正则表达式查找不以标点符号结尾的行。
  • 使用&& NF可以让我们只抓取非空行。
  • 当我们找到这样的行时,我们会使用awk内置变量$NF来保存最后一个字段的值。
  • 我们通过.
  • 向其添加$NF=$NF"."
  • 1用于打印该行,因为它会生成true。

$ cat file
A button is missing!
A button on their back allowed them to hug
A cat is carried by the scruff of its neck by a teenage boy?
A cattery is where cats are commercially housed

$ awk '!/[[:punct:]]$/ && NF{$NF=$NF"."}1' file
A button is missing!
A button on their back allowed them to hug.
A cat is carried by the scruff of its neck by a teenage boy?
A cattery is where cats are commercially housed.

答案 2 :(得分:1)

纯粹的bash解决方案,假设您的消息位于文件msg中:

while read
do
    r=${REPLY: -1}
    if [[ $r != "." ]] && [[ $r != "," ]] && [[ $r != "!" ]] && [[ $r != "?" ]]      
    then
        REPLY="$REPLY." 
    fi
    echo "$REPLY" 
done < msg

r被分配了$REPLY的最后一个字符。

编辑:在较新的bash上,您可以使用[[:punct:]]字符类并使用+=连接字符串。此版本也不会将.添加到空行:

while read
do
    if [[ ! -z "$REPLY" ]] && [[ $REPLY != *[[:punct:]] ]]
    then 
        REPLY+="."
    fi
    echo "$REPLY"
done < msg

答案 3 :(得分:0)

这是使用正则表达式模式匹配的另一个仅使用bash的解决方案,请参阅注释以获取详细信息。如果您的数据在文件中,则必须使用readarray或类似技术将数据导入数组。我只是将文本粘贴到一个数组中,以便在本演示中使用:

#!/usr/bin/env bash

text=(
    "A button is missing!"
    "A button on their back allowed them to hug."
    "A cat is carried by the scruff of its neck by a teenage boy?"
    "A cattery is where cats are commercially housed,"
    "A cattery is where cats are commercially housed" # Demo sentence missing a punctuation
)

# Regex pattern
regex="[!?,.]$"

# Counter used to call the index of the array inside the for loop
counter=0

# Iterate over each sentence inside the array
for sentence in "${text[@]}"; do

    # If a sentence does not match the regex pattern
    # append a dot.
    if [[ ! "$sentence" =~ $regex ]]; then
        text[$counter]="${sentence}."
    fi

    # Increment the counter to get the next item of the array
    (( counter++ ))
done

# We are done print the results
printf "%s\n" "${text[@]}"