0

My problem is that I read a file and got array of strings, but each my string has spaces in the end, I need to remove it. Each line has different numbers of spaces. How can I do this?

Right now I can delete all spaces from each string, it looks like:

My code:

index=0 while read name; do get_user_group_from_file[$index]="${name//[[:space:]]/}" index=$(($index+1)) done < "${FILE}" 

3 Answers 3

2

The problem with your approach is the parameter expansion code removes all spaces from a given input line. For e.g. see

str='line has spaces' echo "${str//[[:space:]]/}" linehasspaces 

To remove only the last one, use a different construct with bash provides with extglob

str='line has 4 spaces last ' echo "${str%%+([[:space:]])}" 

So your whole script should look like

#!/usr/bin/env bash shopt -s extglob while read -r name; do get_user_group_from_file[$index]="${name%%+([[:space:]])}" index=$(($index+1)) done < "${FILE}" 
Sign up to request clarification or add additional context in comments.

2 Comments

@NikitaLitvinov : Click on the tick mark next to answer
index=$(($index+1)) can be written as ((index++)).
1

You can output the file with removed trailing spaces like this:

sed 's/[[:space:]]*$//' "$file" 

example:

> echo "123 " > file > echo "+$(cat file)+" +123 + > echo "+$(sed 's/[[:space:]]*$//' file)+" +123+ 

and another example:

> echo "123 " > file > echo "+$(cat file)+" +123 + > sed -i -e 's/[[:space:]]*$//' file > echo "+$(cat file)+" +123+ 

or remove it from a string saved in a variable:

sed 's/[[:space:]]*$//' <<<"$line" 

example:

> string="alallal "; > string=$(sed 's/[ ]*$//' <<<"$string") > echo "+${string}+" +alallal+ 

The [[:space:]]* matches one or more whitespaces characters (tabs, spaces). If you want only spaces, replace that with just [ ]*. The $ is used to indicate end of line.

To get count of lines in file, use wc -l:

index=$(wc -l < "$FILE") 

Note that:

while read name 

by iteself removes trailing and leading whitespace characters. Also allows backslash to escape characters. Use:

while IFS= read -r name 

More about that topic can be found here.

To read a file into an array without trailing whitespaces, use:

mapfile -t get_user_group_from_file < <(sed 's/[[:space:]]*$//' file) 

2 Comments

I'm sorry, buy it doesn't do what I need. Could you please help me with my code?
while read name removes trailing newlines, don't know what you want to do.
0

I believe you just need to change a line there

get_user_group_from_file[$index]="${name// *$/}" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.