Home > Software design >  Output in one number
Output in one number

Time:11-28

Hello I have a task to count the number of symbolic links (not regular files nor directories etc.) in directory /bin having b as the first letter of their names.

>  find /bin -name "b*" -type l  -printf l  > list.txt

But it outputs

1111

What should I do to change the output to one number (I mean 4) insted of these four 1?

CodePudding user response:

To count correctly also symbolic links with line breaks:

find /bin -name "b*" -type l -printf "l" | wc -c >list.txt

CodePudding user response:

It is possible to count the links in a Bash script by storing the output of find in an array and counting the array entries:

#!/usr/bin/env bash

# Singular|Plural format string
__links_count_format=('There is %d link\n' 'There are %d links\n')

# Capture the links found by the find command into the links array
mapfile -d '' links < <(find /bin -name "b*" -type l -print0)

# Get the links count
links_count="${#links[@]}"

# Print the number of entries/links captured in the array
# shellcheck disable=SC2059 # dynamic format string
printf "${__links_count_format[links_count>1]}" "$links_count"

# Print the links captured in the array
printf '%s\n' "${links[@]}"

CodePudding user response:

-type l will find all the symbolic links and print a 1 for each. Then use wc to count characters

find /bin -name "b*" -type l -printf 1|wc -c > list.txt

CodePudding user response:

You can use below awk based implementation as well

controlplane ~ ➜   find /bin -type l | awk -F'/' '$3 ~ /^f/ {count  }END{print count}'
5

controlplane ~ ➜   find /bin -type l | awk -F'/' '$3 ~ /^b/ {count  }END{print count}'
2

controlplane ~ ➜  
  • Related