如何使用命令行(tcsh)搜索DuckDuckGo?

如何使用命令行(tcsh)搜索DuckDuckGo?

有一个简单的功能,我经常使用它来在网络上查找内容

在鱼中

function ddg
    set URL "https://duckduckgo.com/?q=$(echo "$argv" | tr " " "+")"
    python3 -m webbrowser -t "$URL"
end

在ZSH

ddg() {
    URL="https://duckduckgo.com/?q=$(echo "$*" | tr " " "+")"
    python3 -m webbrowser -t "$URL"
}

但是我现在需要使用 tcsh,但我不知道如何翻译它。

这应该很容易,但我不知道我是否需要eval,如何访问参数等。

我尝试过alias ddg "python3 -m webbrowser -t \"https://duckduckgo.com/?q$(echo '\!*' | tr ' ' '+')\"",但出现以下错误

Illegal variable name.

答案1

tcsh 没有函数。

在很多情况下,您可以解决一些问题,例如,您可以编写一个单独的 tcsh 脚本并将您想要干预的参数传递给该脚本。

但老实说,您已经在使用脚本解释器 python,它可以在您的所有计算机上使用。所以只需编写一个简单的 Python 脚本即可!另外,请注意,您应该对作为 URL 参数传递的内容进行 URL 转义;你根本不在这里这样做:)

此外,你的函数只是将所有空格转换为加号——这不是你想要的;如果您输入ddg cat "toy company",您确实不希望玩具和公司之间的空格转换为加号。另外,您的 shell 函数不会引用包含空格的参数字符串,因此实际上您一直在搜索cat+toy+company,而您本想搜索cat+"toy company"。有所作为!让我们解决这个问题:

#!/usr/bin/env python3
# Save this file somewhere in your $PATH, or make an `alias` that calls it explicitly
# `chmod 755 filename` will make this file executable

import webbrowser
import sys
from urllib.parse import urlencode

if len(sys.argv) < 2:
  """
  no arguments given, just open the DDG homepage
  """
  webbrowser.open("https://duckduckgo.com")
  sys.exit(0)

# enclose arguments that you specifically passed as single argument
# containing space characters with quotation marks
quoted = (f'"{value}"' if " " in value else value for value in sys.argv[1:])
argument = "+".join(quoted)
url = urlencode(f"https://duckduckgo.com/?q{argument}")
webbrowser.open(url)

相关内容