Если вы хотите просмотреть содержимое файла клика, переименуйте его как .tar.gz и Nautilus на свой компьютер, вы увидите его. Наконец, удалите расширение .tar.gz.
Если вам не нужно делать это в чистом bash (по педантичным причинам?), используйте cut для создания списка «первых слов», либо в цикле for wrd in $(cut "-d " -f1 $file_name ) ; do, либо если ваш список слов больше чем xargs --no-run-if-empty --show-limits </dev/null, используйте cut и xargs.
В вашем существующем коде вы, похоже, пытаетесь разбить все данные и используете только bash «Parameter Expansion», обработайте его в content (неправильное использование переменных bash), затем используйте его как имя файла (cat $content), чтобы сгладить данные и обработать 1 строку за раз.
Конечно, прочитайте man cut, man xargs и man bash.
Создайте файл с именем ~/Documents/FirstWord.txt, содержащий:
Sample data file --> FirstWord.txt
This is a simple little input file used
as to test the bash script FirstWord.sh
There are three paragraphs separated by
one blank line. The output from this file
is "Sample", "This", "as", "one" and "is".
Создайте скрипт bash с именем ~/Downloads/FirstWord.sh, содержащий:
!/bin/bash
file_name=$1
content=$(cat $file_name)
content="${content//"\n"/" "}" # <-- You were missing double quotes around
content="${content//". "/"\n"}" # ${content//...} needed when spaces occur.
echo "$content" > /tmp/ContentFile # Create temporary file of massaged data.
declare arr # Define regular array.
while IFS='' read -r line || [[ -n "$line" ]]; do
# ^ 1. ^ 2. ^ 3.
# 1. IFS='' (or IFS=) prevents leading/trailing whitespace from being trimmed.
# 2. -r prevents backslash escapes from being interpreted.
# 3. || [[ -n $line ]] prevents the last line from being ignored if it doesn't end with a \n (since read returns a non-zero exit code when it encounters EOF).
# ** Above explanation from: https://stackoverflow.com/a/10929511/6929343
first=${line%% *} # Extract first word from line.
arr+=($first) # Assign $first to next available array entry.
done < /tmp/ContentFile # <-- In bash it is best to read files at end of while loop.
echo ${arr[@]} # Dump array contents to screen.
rm -f /tmp/ContentFile # Remove temporary file.
# +============================================================================+
# | Original program with comments below |
# +----------------------------------------------------------------------------+
# declare -A arr <-- We don't need associative array.
# cat $content| while read line; <-- Unconventional method
# do <-- I usually append to line above.
# line=($line) <--- Assigning a variable to itself has no effect.
# word=${line[0]} < Not sure what would be accomplished by this.
# if [[ ${arr[$word]} == '' ]] <-- I've indented for readability.
# then
# arr[$word]=1 <-- "word" isn't a counter, won't work.
# else
# let arr[$word]=${arr[$word]}+1<-- Once again "word" isn't a counter.
# fi
# done <-- Where input to while loop shoud be.
Сохраните два файла, а затем в Тип терминала:
~$ cd Downloads
~/Downloads$ chmod a+x FirstWord.sh
~/Downloads$ ./FirstWord.sh FirstWord.txt
Sample This as There one is
Если вам не нужно делать это в чистом bash (по педантичным причинам?), используйте cut для создания списка «первых слов», либо в цикле for wrd in $(cut "-d " -f1 $file_name ) ; do, либо если ваш список слов больше чем xargs --no-run-if-empty --show-limits </dev/null, используйте cut и xargs.
В вашем существующем коде вы, похоже, пытаетесь разбить все данные и используете только bash «Parameter Expansion», обработайте его в content (неправильное использование переменных bash), затем используйте его как имя файла (cat $content), чтобы сгладить данные и обработать 1 строку за раз.
Конечно, прочитайте man cut, man xargs и man bash.
Создайте файл с именем ~/Documents/FirstWord.txt, содержащий:
Sample data file --> FirstWord.txt
This is a simple little input file used
as to test the bash script FirstWord.sh
There are three paragraphs separated by
one blank line. The output from this file
is "Sample", "This", "as", "one" and "is".
Создайте скрипт bash с именем ~/Downloads/FirstWord.sh, содержащий:
!/bin/bash
file_name=$1
content=$(cat $file_name)
content="${content//"\n"/" "}" # <-- You were missing double quotes around
content="${content//". "/"\n"}" # ${content//...} needed when spaces occur.
echo "$content" > /tmp/ContentFile # Create temporary file of massaged data.
declare arr # Define regular array.
while IFS='' read -r line || [[ -n "$line" ]]; do
# ^ 1. ^ 2. ^ 3.
# 1. IFS='' (or IFS=) prevents leading/trailing whitespace from being trimmed.
# 2. -r prevents backslash escapes from being interpreted.
# 3. || [[ -n $line ]] prevents the last line from being ignored if it doesn't end with a \n (since read returns a non-zero exit code when it encounters EOF).
# ** Above explanation from: https://stackoverflow.com/a/10929511/6929343
first=${line%% *} # Extract first word from line.
arr+=($first) # Assign $first to next available array entry.
done < /tmp/ContentFile # <-- In bash it is best to read files at end of while loop.
echo ${arr[@]} # Dump array contents to screen.
rm -f /tmp/ContentFile # Remove temporary file.
# +============================================================================+
# | Original program with comments below |
# +----------------------------------------------------------------------------+
# declare -A arr <-- We don't need associative array.
# cat $content| while read line; <-- Unconventional method
# do <-- I usually append to line above.
# line=($line) <--- Assigning a variable to itself has no effect.
# word=${line[0]} < Not sure what would be accomplished by this.
# if [[ ${arr[$word]} == '' ]] <-- I've indented for readability.
# then
# arr[$word]=1 <-- "word" isn't a counter, won't work.
# else
# let arr[$word]=${arr[$word]}+1<-- Once again "word" isn't a counter.
# fi
# done <-- Where input to while loop shoud be.
Сохраните два файла, а затем в Тип терминала:
~$ cd Downloads
~/Downloads$ chmod a+x FirstWord.sh
~/Downloads$ ./FirstWord.sh FirstWord.txt
Sample This as There one is