简体   繁体   中英

greping a character from file UNIX.linux bash. Can't pass an argument(file name) through command line

I am having trouble with my newbie linux script which needs to count brackets and tell if they are matched.

#!/bin/bash

    file="$1"
    x="()(((a)(()))"
    left=$(grep -o "(" <<<"$x" | wc -l) 
    rght=$(grep -o ")" <<<"$x" | wc -l)

    echo "left = $left right = $rght"
    if [ $left -gt $rght ]
       then echo "not enough brackets"
    elif [ $left -eq $rght ]
       then echo "all brackets are fine"
    else echo "too many" 
    fi

the problem here is i can't pass an argument through command line so that grep would work and count the brackets from the file. In the $x place I tried writing $file but it does not work

I am executing the script by writting: ./script.h test1.txt the file test1.txt is on the same folder as script.h

Any help in explaining how the parameter passing works would be great. Or maybe other way to do this script?

The construct <<< is used to transmit "the contents of a variable", It is not applicable to "contents of files". If you execute this snippet, you could see what I mean:

#!/bin/bash
file="()(((a)((a simple test)))"
echo "$( cat <<<"$file" )"

which is also equivalent to just echo "$file" . That is, what is being sent to the console are the contents of the variable "file".

To get the "contents of a file" which name is inside a var called "file", then do:

#!/bin/bash
file="test1.txt"
echo "$( cat <"$file" )"

which is exactly equivalent to echo "$( <"$file" )" , cat <"$file" or even <"$file" cat You can use: grep -o "(" <"$file" or <"$file" grep -o "(" But grep could accept a file as a parameter, so this: grep -o "(" "$file" also works.

However, I believe that tr would be a better command, as this: <"$file" tr -cd "(" .
It transforms the whole file into a sequence of "(" only, which will need a lot less to be transmitted (passed) to the wc command. Your script would become, then:

#!/bin/bash -
file="$1"

[[    $file ]] || exit 1    # make sure the var "file" is not empty.
[[ -r $file ]] || exit 2    # test if the file "file" exists.

left=$(<"$file" tr -cd "("| wc -c) 
rght=$(<"$file" tr -cd ")"| wc -c)

echo "left = $left right = $rght"

# as $left and $rght are strictly numeric values, this integer tests work:
(( $left >  $rght )) && echo "not enough right brackets"
(( $left == $rght )) && echo "all brackets are fine"
(( $left <  $rght )) && echo "too many right brackets"

# added as per an additional request of the OP.
if [[ $(<"$file" tr -cd "()"|head -c1) = ")" ]]; then 
    echo "the first character is (incorrectly) a right bracket"
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM