Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Native way to check if an entry is one line?

Tags:

find

bash

wc

I have a find script that automatically opens a file if just one file is found. The way I currently handle it is doing a word count on the number of lines of the search results. Is there an easier way to do this?

if [ "$( cat "$temp" | wc -l | xargs echo )" == "1" ]; then
    edit `cat "$temp"`
fi

EDITED - here is the context of the whole script.

term="$1"
temp=".aafind.txt"

find src sql common -iname "*$term*" | grep -v 'src/.*lib'  >> "$temp"

if [ ! -s "$temp" ]; then
    echo "ø - including lib..." 1>&2
    find src sql common -iname "*$term*"  >> "$temp"
fi


if [ "$( cat "$temp" | wc -l | xargs echo )" == "1" ]; then
    # just open it in an editor
    edit `cat "$temp"`
else
    # format output
    term_regex=`echo "$term" | sed "s%\*%[^/]*%g" | sed "s%\?%[^/]%g" `
    cat "$temp" | sed -E 's%//+%/%' | grep --color -E -i "$term_regex|$"
fi

rm "$temp"
like image 551
redolent Avatar asked Dec 06 '22 03:12

redolent


1 Answers

Unless I'm misunderstanding, the variable $temp contains one or more filenames, one per line, and if there is only one filename it should be edited?

[ $(wc -l <<< "$temp") = "1" ] && edit "$temp"

If $temp is a file containing filenames:

[ $(wc -l < "$temp") = "1" ] && edit "$(cat "$temp")"
like image 155
grebneke Avatar answered Feb 04 '23 23:02

grebneke