More of a curiosity of if and how it can be done. I sometimes find myself repeating commands with small parts of the same command modified.
Example:
grep aaa file.txt
grep bbb file.txt
grep ccc file.txt
I know I could set this up with a for loop but I don't always know all of the values that may need to be changed/tested at start. I can also use keyboard movement to get back to the aaa quicker, but it's still extra keys. Not a lot with the example, but some strung together commands can result in a lot of keyboard movement needed.
I know that variables and files can be passed to certain commands at the end, for example.
while read i; do echo "$i"; done < ./file.txt
x='./file.txt'
sed 's/find/replace/' <<<${x}
I'm curious if there is a way with bash substitution to do similar declaration at the end of the command for undeclared variables. I tried variations like grep ${} file.txt <<< 'aaa'
but so far nothing I've toyed with has worked out. My goal is that the passed value is not declared as a variable so I can just hit up arrow on keyboard and edit the string at the end of the command statement. Appreciate any help or insights that can be given!
CodePudding user response:
You can define a quick function:
f () { grep "$1" file.txt; }
Now you can run
f aaa
f bbb
f ccc
f
is probably shorter than any key sequence that can pull up a previous command to edit :) Plus, the portion you want to change is now the final argument, making it simpler to edit if you do use up-arrow to bring up the last command.
CodePudding user response:
Thanks for the feedback everyone! I found another solution as well.
xargs -I {} grep {} file.txt <<< aaa
CodePudding user response:
Bash also supports substitution of the last command via ^old^new^
:
$ grep shy lyrics.txt
You're too shy to say it
You're too shy to say it
$ ^shy^cry^
grep cry lyrics.txt
Never gonna make you cry
Never gonna make you cry
...